package top.songxs.yygh.hosp.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import top.songxs.yygh.model.cmn.Dict;
import top.songxs.yygh.hosp.cmn.mapper.DictMapper;
import top.songxs.yygh.hosp.cmn.readlistener.DictReadListener;
import top.songxs.yygh.hosp.cmn.service.DictService;
import top.songxs.yygh.vo.cmn.DictEeVo;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    RedisTemplate redisTemplate;


    //不同的命名空间存储不同类型的缓存  value
    //key 的格式  key 对应的value是  方法return的返回值
    @Override
    @Cacheable(value = "dict_cache", key = "'dict_list_'+#id")
    public List<Dict> findChildData(Long id) {
        //添加查询
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        List<Dict> list = this.list(queryWrapper);
        list.forEach(dict -> {
            Boolean b = isChildren(dict);
            dict.setHasChildren(b);
        });
        return list;
    }

    @Override
    public void exportData(HttpServletResponse response) {


        try {
            //设置下载需要的一些响应头
            //字符编码
            response.setCharacterEncoding("UTF-8");
            //响应数据类型
            response.setContentType("application/vnd.ms-excel");
            //下载文件名需要的编码
            String filename = "数据字典列表.xlsx";

            response.addHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(filename, "utf-8"));
            //查询数据库中的数据
            List<Dict> list = this.list();
            //数据格式转换
            String json = JSONObject.toJSONString(list);
            List<DictEeVo> dictEeVos = JSONObject.parseArray(json, DictEeVo.class);
            //导入数据
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet().doWrite(dictEeVos);
        } catch (Exception e) {

        }


    }


    @Autowired
    DictReadListener dictReadListener;

    @Override
    @CacheEvict(value = "dict_cache", beforeInvocation = true, allEntries = true)
    //vale : 清空哪一个命名空间下的 缓存  beforeInvocation 执行方法体之前还是之后清空 true ： 之前
    //allEntries : 是否清空该命名空间下所有缓存
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, dictReadListener).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getName(String value, String dictCode) {

        //根据 value查询
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("value", value);
        if (!StringUtils.isEmpty(dictCode)) {
            //根据value和dictCode查询
            queryWrapper.eq("parent_id", this.getDict(dictCode).getId());
        }
        return baseMapper.selectOne(queryWrapper).getName();

    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //条件查询
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        //todo: 锚点
        queryWrapper.eq("parent_id",this.getDict(dictCode).getId());

        return baseMapper.selectList(queryWrapper);
    }

    private Dict getDict(String dictCode) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code", dictCode);
        return baseMapper.selectOne(queryWrapper);

    }


    private Boolean isChildren(Dict dict) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", dict.getId());
        Integer count = this.count(queryWrapper);
        return count > 0;
    }
}
